#!/usr/bin/env python3
"""
修复 Markdown 表格分隔行列数不一致问题，使所有分隔行与表头/数据行对齐。
用法：python3 scripts/fix_md_table_separators.py config/protocols/monet/monet.md
"""
import sys, re

if len(sys.argv) < 2:
    print("usage: fix_md_table_separators.py file.md")
    sys.exit(2)

path = sys.argv[1]
with open(path, 'r', encoding='utf-8') as f:
    lines = f.readlines()

out = []
changed = False
for i, line in enumerate(lines):
    # 检查分隔行：只包含 | - : 空格
    if re.match(r'^\s*\|[\s\-:|]+\|\s*$', line):
        # 查找前一行（表头）有多少个 |
        j = i-1
        while j >= 0 and not lines[j].strip().startswith('|'):
            j -= 1
        if j >= 0:
            n = lines[j].count('|')
            # 当前分隔行 | 数量
            cur = line.count('|')
            if cur != n:
                # 生成新的分隔行
                # 拆分表头，生成对应数量的 ---
                cells = ['---'] * (n-1)
                new_line = '|' + '|'.join(cells) + '|' + '\n'
                out.append(new_line)
                changed = True
                continue
    out.append(line)

if changed:
    bak = path + '.bak'
    with open(bak, 'w', encoding='utf-8') as f:
        f.writelines(lines)
    with open(path, 'w', encoding='utf-8') as f:
        f.writelines(out)
    print(f"Fixed table separators in {path}; backup at {bak}")
else:
    print(f"No changes needed for {path}")
